<template>
  <view class="message-box-container px-14">
    <!-- 功能按钮行（完全保留注释代码） -->
    <view class="function-buttons">
      <view class="deep-think" :class="{ active: isDeepThink }" @click="toggleDeepThink">
        <image mode="aspectFit" :src="isDeepThink ? deepThinkActiveIcon : deepTinkingIcon" class="deep-think-icon senderBtn-icon" />
        <text class="button-text">深度思考</text>
      </view>

      <view class="network-switch" :class="{ active: isNetworking }" @click="toggleNetwork">
        <image mode="aspectFit" :src="isNetworking ? networkActiveIcon : networkIcon" class="senderBtn-icon" />
        <text class="button-text">联网开关</text>
      </view>
    </view>

    <view class="message-box">
      <view class="message-box-main">
        <!-- 新增图片预览列表 -->
        <view class="image-preview-list" v-if="uploadedImages.length > 0">
          <scroll-view scroll-x="true" class="image-scroll">
            <view class="image-item" v-for="item in uploadedImages" :key="item.id">
              <image :src="item.fileFullPath" mode="aspectFill" class="preview-image"></image>
              <view class="delete-icon" @click="removeImage(item)">
                <uni-icons type="closeempty" size="12" color="#fff"></uni-icons>
              </view>
            </view>
          </scroll-view>
        </view>

        <view class="message-box-inner">
          <!-- 拍照按钮（添加聚焦隐藏逻辑） -->
          <view class="icon-wrapper" v-if="!isInputFocused" @click="handleCamera">
            <uni-icons type="camera" size="26" color="#000"></uni-icons>
          </view>

          <!-- 输入框（添加聚焦事件） -->
          <input
            class="input-box"
            type="text"
            v-model.trim="message"
            placeholder="发送消息..."
            placeholder-class="placeholder"
            confirm-type="send"
            @confirm="handleSend"
            @focus="isInputFocused = true"
            @blur="isInputFocused = false" />

          <!-- 右侧按钮（动态切换） -->
          <view class="icon-wrapper">
            <uni-icons v-if="!chatLoading && message" type="arrow-up" size="22" color="#1678FF" class="send-arrow" @click="handleSend"></uni-icons>
            <uni-icons v-else-if="chatLoading" type="loop" size="22" color="#1678FF" class="send-arrow spinner-2" @click="stopChat"></uni-icons>
            <uni-icons v-else :type="showMore ? 'minus' : 'plus'" size="26" color="#000" @click="toggleMore"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 扩展功能区（完全未修改） -->
      <view v-if="showMore" class="more-options">
        <view class="options-container">
          <view class="option-item" @click="handleCamera">
            <uni-icons type="camera" size="30" color="#000"></uni-icons>
            <text class="option-text">拍照</text>
          </view>
          <view class="option-item" @click="handleImage">
            <uni-icons type="image" size="30" color="#000"></uni-icons>
            <text class="option-text">图片</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import deepTinkingIcon from '@/static/chat/deep-think-icon.png';
  import deepThinkActiveIcon from '@/static/chat/deep-think-active-icon.png';
  import networkIcon from '@/static/chat/network-icon.png';
  import networkActiveIcon from '@/static/chat/network-active-icon.png';
  import { useChatStore } from '@/store/chat';
  import { mapState } from 'pinia';
  import { uploadAction, previewFile } from '@/api/uploadConfig';
  import { timeout } from '@/api/request';
  import { useUserStore } from '@/store/user';

  export default {
    data() {
      return {
        message: '',
        showMore: false,
        isInputFocused: false,
        deepTinkingIcon,
        deepThinkActiveIcon,
        networkIcon,
        networkActiveIcon,
        uploadedImages: [],
        maxFileNum: 10
      };
    },
    props: {
      chatLoading:{
        default: false
      }
    },
    computed: {
      ...mapState(useChatStore, ['isDeepThink', 'isNetworking'])
    },
    methods: {
      toggleDeepThink() {
        const userStore = useChatStore();
        userStore.setIsDeepThink(!this.isDeepThink);
      },
      toggleNetwork() {
        const userStore = useChatStore();
        userStore.setIsNetworking(!this.isNetworking);
      },
      toggleMore() {
        this.showMore = !this.showMore;
      },
      handleSend() {
        if (this.message) {
          this.$emit('send', this.message, this.uploadedImages);
          this.message = '';
          this.uploadedImages = [];
        } else {
          this.message = '';
          uni.showToast({
            title: '请输入要发送的消息',
            icon: 'none'
          });
        }
      },
      stopChat(){
        this.$emit('stop');
      },
      removeImage(item) {
        this.uploadedImages = this.uploadedImages.filter(item => item.id !== item.id);
      },
      checkMaxFileNum() {
        if (this.uploadedImages.length >= this.maxFileNum) {
          uni.showToast({
            title: `最多上传${this.maxFileNum}个图片`,
            icon: 'none'
          });
          return false;
        }
        return true;
      },
      handleCamera() {
        if(this.chatLoading){
          uni.showToast({ title: '请稍等，正在生成中...',icon:'none' });
          return;
        }
        if (!this.checkMaxFileNum()) {
          return;
        }
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['camera'],
          success: res => {
            const imageUrl = res.tempFilePaths[0];
            this.uploadFile(imageUrl);
          }
        });
      },
      handleImage() {
        if (!this.checkMaxFileNum()) {
          return;
        }
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album'],
          extension: ['png', 'jpg', 'jpeg', 'gif', 'webp'],
          success: res => {
            const imageUrl = res.tempFilePaths[0];
            this.uploadFile(imageUrl);
          },
          fail: err => {
            uni.showToast({
              title: '请选择有效的图片文件',
              icon: 'none'
            });
          }
        });
      },
      // 上传图片到服务器
      uploadFile(filePath) {
        uni.showLoading({
          title: '上传中...'
        });

        const userStore = useUserStore();

        uni.uploadFile({
          url: uploadAction,
          filePath: filePath,
          name: 'file',
          timeout,
          header: {
            Authorization: userStore.token
          },
          success: uploadRes => {
            uni.hideLoading();
            try {
              const data = JSON.parse(uploadRes.data);
              
              const { fileUrl, id, originalFilename, fileSize } = data;
              const fileFullPath = `${previewFile}/${fileUrl}`;

              this.uploadedImages.push({
                id,
                fileFullPath,
                fileUrl,
                originalFilename,
                fileSize
              })

              uni.showToast({
                title: '上传成功',
                icon: 'success'
              });
            } catch (e) {
              uni.showToast({
                title: '上传数据解析失败',
                icon: 'none'
              });
            }
          },
          fail: err => {
            uni.hideLoading();
            this.uploadResult = '上传失败: ' + err.errMsg;
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  /* 完全保留原有样式 */
  .message-box-container {
    width: 100%;
    box-sizing: border-box;
    padding-bottom: 20rpx;

    .function-buttons {
      display: flex;
      gap: 20rpx;
      margin-bottom: 20rpx;

      .deep-think,
      .network-switch {
        display: flex;
        align-items: center;
        gap: 8rpx;
        justify-content: center;
        padding: 12rpx 16rpx;
        background: #f7f9fa;
        border: 1rpx solid #c4c4c4;
        border-radius: 20rpx;
        transition: all 0.3s ease;

        .senderBtn-icon {
          width: 30rpx;
          height: 30rpx;
        }

        .deep-think-icon {
          width: 26rpx;
          height: 26rpx;
        }

        &:active {
          opacity: 0.8;
        }

        .button-text {
          font-size: 26rpx;
          color: #222222;
          line-height: 1.1;
        }

        &.active {
          background: #eaf5ff;
          border-color: #7caff5;

          .button-text {
            color: #1678ff;
          }
        }
      }
    }

    .message-box {
      width: 100%;
      transition: height 0.3s ease;
      overflow: hidden;

      .message-box-main {
        box-sizing: border-box;
        background-color: #fff;
        border-radius: 26rpx;
        padding: 15rpx 20rpx;

        /* 新增图片预览列表样式 */
        .image-preview-list {
          margin-bottom: 20rpx;
          height: 100rpx;

          .image-scroll {
            white-space: nowrap;
            height: 100%;

            .image-item {
              display: inline-block;
              position: relative;
              width: 100rpx;
              height: 100rpx;
              margin-right: 10rpx;

              .preview-image {
                width: 100%;
                height: 100%;
                border-radius: 8rpx;
              }

              .delete-icon {
                position: absolute;
                top: 2rpx;
                right: 2rpx;
                width: 26rpx;
                height: 26rpx;
                background-color: #dc1414;
                border: 2rpx solid #fff;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 1;
              }
            }
          }
        }
      }

      .message-box-inner {
        display: flex;
        align-items: center;
        height: 90rpx - 26rpx;
        box-sizing: border-box;

        .icon-wrapper {
          width: 60rpx;
          height: 60rpx;
          display: flex;
          align-items: center;
          justify-content: center;

          /* 新增发送箭头样式（不影响原有样式） */
          .send-arrow {
            background: #eaf5ff;
            border-radius: 50%;
            padding: 5rpx;
          }
        }

        .input-box {
          flex: 1;
          height: 60rpx;
          margin: 0 20rpx;
          font-size: 28rpx;

          &.placeholder {
            color: #999;
            font-size: 28rpx;
          }
        }
      }

      .more-options {
        display: flex;
        justify-content: flex-start;
        border-top: 1rpx solid #eee;
        height: 140rpx;
        box-sizing: border-box;
        margin-top: 24rpx;

        .options-container {
          display: flex;
          gap: 20rpx;

          .option-item {
            width: 120rpx;
            height: 120rpx;
            background: #dfe3ea;
            border-radius: 9px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            .option-text {
              font-size: 24rpx;
              line-height: 1.1;
              color: #000;
            }
          }
        }
      }
    }
  }
</style>
